# 创建监控分析页面
<template>
  <div class="monitor-analysis">
    <!-- 监控指标概览 -->
    <el-row :gutter="20" class="metric-overview">
      <el-col :span="6" v-for="metric in metrics" :key="metric.key">
        <el-card shadow="hover" class="metric-card">
          <template #header>
            <div class="card-header">
              <span>{{ metric.label }}</span>
              <el-tag :type="getMetricStatusType(metric.value, metric.threshold)">
                {{ getMetricStatusLabel(metric.value, metric.threshold) }}
              </el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="metric-value">
              <span class="value">{{ formatMetricValue(metric.value, metric.unit) }}</span>
              <span class="trend" :class="getTrendClass(metric.trend)">
                {{ formatTrend(metric.trend) }}
                <el-icon v-if="metric.trend > 0"><ArrowUp /></el-icon>
                <el-icon v-else-if="metric.trend < 0"><ArrowDown /></el-icon>
              </span>
            </div>
            <div class="metric-chart">
              <div ref="metricChartRefs[metric.key]" class="chart-container"></div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 监控分析图表 -->
    <el-row :gutter="20" class="analysis-charts">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>系统调用趋势</span>
              <div class="header-operations">
                <el-radio-group v-model="callTrendTimeRange" size="small">
                  <el-radio-button label="1h">1小时</el-radio-button>
                  <el-radio-button label="6h">6小时</el-radio-button>
                  <el-radio-button label="24h">24小时</el-radio-button>
                  <el-radio-button label="7d">7天</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <div ref="callTrendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>性能指标对比</span>
              <div class="header-operations">
                <el-select v-model="comparisonTimeRange" size="small">
                  <el-option label="今日 vs 昨日" value="today_vs_yesterday" />
                  <el-option label="本周 vs 上周" value="this_week_vs_last_week" />
                  <el-option label="本月 vs 上月" value="this_month_vs_last_month" />
                </el-select>
              </div>
            </div>
          </template>
          <div ref="comparisonChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="analysis-charts">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>资源使用分布</span>
              <div class="header-operations">
                <el-select v-model="resourceType" size="small">
                  <el-option label="CPU使用率" value="cpu" />
                  <el-option label="内存使用率" value="memory" />
                  <el-option label="磁盘使用率" value="disk" />
                  <el-option label="网络带宽" value="network" />
                </el-select>
              </div>
            </div>
          </template>
          <div ref="resourceChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>告警趋势分析</span>
              <div class="header-operations">
                <el-select v-model="alertAnalysisType" size="small">
                  <el-option label="告警数量" value="count" />
                  <el-option label="告警级别" value="level" />
                  <el-option label="告警类型" value="type" />
                  <el-option label="处理时间" value="process_time" />
                </el-select>
              </div>
            </div>
          </template>
          <div ref="alertAnalysisChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 监控数据表格 -->
    <el-card class="monitor-table" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>监控数据明细</span>
          <div class="header-operations">
            <el-input
              v-model="tableSearch"
              placeholder="搜索监控数据"
              style="width: 200px"
              clearable
              @clear="handleTableSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleExportData">导出数据</el-button>
            <el-button @click="handleRefreshData">刷新</el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="monitorData"
        border
        v-loading="tableLoading"
        style="width: 100%"
      >
        <el-table-column prop="timestamp" label="时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.timestamp) }}
          </template>
        </el-table-column>
        <el-table-column prop="metric" label="监控指标" width="150" />
        <el-table-column prop="value" label="数值" width="120">
          <template #default="{ row }">
            {{ formatMetricValue(row.value, row.unit) }}
          </template>
        </el-table-column>
        <el-table-column prop="threshold" label="阈值" width="120">
          <template #default="{ row }">
            {{ formatMetricValue(row.threshold, row.unit) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getMetricStatusType(row.value, row.threshold)">
              {{ getMetricStatusLabel(row.value, row.threshold) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="trend" label="趋势" width="120">
          <template #default="{ row }">
            <span :class="getTrendClass(row.trend)">
              {{ formatTrend(row.trend) }}
              <el-icon v-if="row.trend > 0"><ArrowUp /></el-icon>
              <el-icon v-else-if="row.trend < 0"><ArrowDown /></el-icon>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" />
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="tablePage"
          v-model:page-size="tablePageSize"
          :total="tableTotal"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleTablePageSizeChange"
          @current-change="handleTablePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import {
  getSystemMonitorData,
  getSystemTrendData,
  getSystemPerformanceData,
  getAlertList,
  exportSystemLogs
} from '@/api/message'

// 监控指标数据
const metrics = reactive([
  {
    key: 'cpu',
    label: 'CPU使用率',
    value: 0,
    unit: '%',
    threshold: 80,
    trend: 0,
    chart: null
  },
  {
    key: 'memory',
    label: '内存使用率',
    value: 0,
    unit: '%',
    threshold: 85,
    trend: 0,
    chart: null
  },
  {
    key: 'disk',
    label: '磁盘使用率',
    value: 0,
    unit: '%',
    threshold: 90,
    trend: 0,
    chart: null
  },
  {
    key: 'network',
    label: '网络带宽使用率',
    value: 0,
    unit: '%',
    threshold: 75,
    trend: 0,
    chart: null
  }
])

// 图表引用
const metricChartRefs = reactive({})
const callTrendChartRef = ref(null)
const comparisonChartRef = ref(null)
const resourceChartRef = ref(null)
const alertAnalysisChartRef = ref(null)

// 图表实例
let callTrendChart = null
let comparisonChart = null
let resourceChart = null
let alertAnalysisChart = null

// 时间范围选择
const callTrendTimeRange = ref('24h')
const comparisonTimeRange = ref('today_vs_yesterday')
const resourceType = ref('cpu')
const alertAnalysisType = ref('count')

// 表格数据
const monitorData = ref([])
const tableLoading = ref(false)
const tablePage = ref(1)
const tablePageSize = ref(20)
const tableTotal = ref(0)
const tableSearch = ref('')

// 初始化
onMounted(async () => {
  await initCharts()
  loadMonitorData()
  
  // 定时刷新数据
  const timer = setInterval(loadMonitorData, 30000)
  
  onUnmounted(() => {
    clearInterval(timer)
    destroyCharts()
  })
})

// 初始化图表
const initCharts = async () => {
  await nextTick()
  
  // 初始化指标小图表
  metrics.forEach(metric => {
    const chartDom = metricChartRefs[metric.key]
    if (chartDom) {
      metric.chart = echarts.init(chartDom)
      updateMetricChart(metric)
    }
  })
  
  // 初始化系统调用趋势图
  if (callTrendChartRef.value) {
    callTrendChart = echarts.init(callTrendChartRef.value)
    updateCallTrendChart()
  }
  
  // 初始化性能对比图
  if (comparisonChartRef.value) {
    comparisonChart = echarts.init(comparisonChartRef.value)
    updateComparisonChart()
  }
  
  // 初始化资源分布图
  if (resourceChartRef.value) {
    resourceChart = echarts.init(resourceChartRef.value)
    updateResourceChart()
  }
  
  // 初始化告警分析图
  if (alertAnalysisChartRef.value) {
    alertAnalysisChart = echarts.init(alertAnalysisChartRef.value)
    updateAlertAnalysisChart()
  }
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
}

// 销毁图表
const destroyCharts = () => {
  metrics.forEach(metric => {
    metric.chart?.dispose()
  })
  callTrendChart?.dispose()
  comparisonChart?.dispose()
  resourceChart?.dispose()
  alertAnalysisChart?.dispose()
  window.removeEventListener('resize', handleResize)
}

// 处理窗口大小变化
const handleResize = () => {
  metrics.forEach(metric => {
    metric.chart?.resize()
  })
  callTrendChart?.resize()
  comparisonChart?.resize()
  resourceChart?.resize()
  alertAnalysisChart?.resize()
}

// 加载监控数据
const loadMonitorData = async () => {
  try {
    const [monitorRes, trendRes, performanceRes, alertRes] = await Promise.all([
      getSystemMonitorData({ timeRange: callTrendTimeRange.value }),
      getSystemTrendData({ timeRange: callTrendTimeRange.value }),
      getSystemPerformanceData({ timeRange: comparisonTimeRange.value }),
      getAlertList({ type: alertAnalysisType.value })
    ])
    
    // 更新指标数据
    updateMetrics(monitorRes.data)
    
    // 更新图表数据
    updateCallTrendChart(trendRes.data)
    updateComparisonChart(performanceRes.data)
    updateResourceChart(monitorRes.data)
    updateAlertAnalysisChart(alertRes.data)
    
    // 更新表格数据
    updateTableData(monitorRes.data)
  } catch (error) {
    console.error('加载监控数据失败:', error)
    ElMessage.error('加载监控数据失败')
  }
}

// 更新指标数据
const updateMetrics = (data) => {
  metrics.forEach(metric => {
    const metricData = data[metric.key]
    if (metricData) {
      metric.value = metricData.value
      metric.trend = metricData.trend
      updateMetricChart(metric, metricData.history)
    }
  })
}

// 更新指标小图表
const updateMetricChart = (metric, history = []) => {
  if (!metric.chart) return
  
  const option = {
    grid: {
      top: 0,
      right: 0,
      bottom: 0,
      left: 0
    },
    xAxis: {
      type: 'category',
      show: false,
      data: history.map((_, index) => index)
    },
    yAxis: {
      type: 'value',
      show: false
    },
    series: [
      {
        data: history.map(item => item.value),
        type: 'line',
        smooth: true,
        symbol: 'none',
        areaStyle: {
          opacity: 0.1
        },
        lineStyle: {
          width: 2
        }
      }
    ]
  }
  
  metric.chart.setOption(option)
}

// 更新系统调用趋势图
const updateCallTrendChart = (data = []) => {
  if (!callTrendChart) return
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['调用次数', '成功率', '平均响应时间']
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.time)
    },
    yAxis: [
      {
        type: 'value',
        name: '调用次数',
        position: 'left'
      },
      {
        type: 'value',
        name: '成功率/响应时间',
        position: 'right',
        axisLabel: {
          formatter: '{value}%'
        }
      }
    ],
    series: [
      {
        name: '调用次数',
        type: 'bar',
        data: data.map(item => item.count)
      },
      {
        name: '成功率',
        type: 'line',
        yAxisIndex: 1,
        data: data.map(item => item.successRate)
      },
      {
        name: '平均响应时间',
        type: 'line',
        yAxisIndex: 1,
        data: data.map(item => item.avgResponseTime)
      }
    ]
  }
  
  callTrendChart.setOption(option)
}

// 更新性能对比图
const updateComparisonChart = (data = {}) => {
  if (!comparisonChart) return
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['当前', '对比']
    },
    xAxis: {
      type: 'category',
      data: data.metrics || []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '当前',
        type: 'bar',
        data: data.current || []
      },
      {
        name: '对比',
        type: 'bar',
        data: data.comparison || []
      }
    ]
  }
  
  comparisonChart.setOption(option)
}

// 更新资源分布图
const updateResourceChart = (data = {}) => {
  if (!resourceChart) return
  
  const resourceData = data[resourceType.value] || {}
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: resourceData.used || 0, name: '已使用' },
          { value: resourceData.available || 0, name: '可用' }
        ]
      }
    ]
  }
  
  resourceChart.setOption(option)
}

// 更新告警分析图
const updateAlertAnalysisChart = (data = []) => {
  if (!alertAnalysisChart) return
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.time)
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        type: 'line',
        smooth: true,
        data: data.map(item => item.value),
        areaStyle: {
          opacity: 0.1
        }
      }
    ]
  }
  
  alertAnalysisChart.setOption(option)
}

// 更新表格数据
const updateTableData = (data) => {
  monitorData.value = Object.entries(data).map(([key, value]) => ({
    timestamp: new Date().toISOString(),
    metric: getMetricLabel(key),
    value: value.value,
    unit: getMetricUnit(key),
    threshold: value.threshold,
    status: getMetricStatus(value.value, value.threshold),
    trend: value.trend,
    description: value.description
  }))
  
  tableTotal.value = monitorData.value.length
}

// 工具方法
const getMetricLabel = (key) => {
  const metric = metrics.find(m => m.key === key)
  return metric ? metric.label : key
}

const getMetricUnit = (key) => {
  const metric = metrics.find(m => m.key === key)
  return metric ? metric.unit : ''
}

const getMetricStatus = (value, threshold) => {
  if (value >= threshold) return 'error'
  if (value >= threshold * 0.8) return 'warning'
  return 'success'
}

const getMetricStatusType = (value, threshold) => {
  return getMetricStatus(value, threshold)
}

const getMetricStatusLabel = (value, threshold) => {
  const status = getMetricStatus(value, threshold)
  const labelMap = {
    success: '正常',
    warning: '警告',
    error: '异常'
  }
  return labelMap[status]
}

const getTrendClass = (trend) => {
  if (trend > 0) return 'trend-up'
  if (trend < 0) return 'trend-down'
  return ''
}

const formatTrend = (trend) => {
  if (trend > 0) return `+${trend.toFixed(1)}%`
  if (trend < 0) return `${trend.toFixed(1)}%`
  return '0%'
}

const formatMetricValue = (value, unit) => {
  return `${value.toFixed(1)}${unit}`
}

const formatDateTime = (timestamp) => {
  return new Date(timestamp).toLocaleString()
}

// 事件处理
const handleTableSearch = () => {
  tablePage.value = 1
  loadMonitorData()
}

const handleTablePageSizeChange = (val) => {
  tablePageSize.value = val
  loadMonitorData()
}

const handleTablePageChange = (val) => {
  tablePage.value = val
  loadMonitorData()
}

const handleExportData = async () => {
  try {
    const res = await exportSystemLogs({
      search: tableSearch.value
    })
    
    const blob = new Blob([res.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `监控数据_${new Date().getTime()}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('导出数据失败:', error)
    ElMessage.error('导出数据失败')
  }
}

const handleRefreshData = () => {
  loadMonitorData()
}
</script>

<style lang="scss" scoped>
.monitor-analysis {
  padding: 20px;
  
  .metric-overview {
    margin-bottom: 20px;
    
    .metric-card {
      height: 100%;
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      
      .card-content {
        .metric-value {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 10px;
          
          .value {
            font-size: 24px;
            font-weight: bold;
          }
          
          .trend {
            display: flex;
            align-items: center;
            gap: 4px;
            
            &.trend-up {
              color: #f56c6c;
            }
            
            &.trend-down {
              color: #67c23a;
            }
          }
        }
        
        .metric-chart {
          height: 50px;
          
          .chart-container {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
  }
  
  .analysis-charts {
    margin-bottom: 20px;
    
    .chart-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .header-operations {
          display: flex;
          align-items: center;
          gap: 10px;
        }
      }
      
      .chart-container {
        height: 300px;
      }
    }
  }
  
  .monitor-table {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-operations {
        display: flex;
        align-items: center;
        gap: 10px;
      }
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style> 